package com.example.shardingjdbc.config;

import cn.hutool.core.date.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.Date;


/**
 * 4.1version 精准分片
 * 根据月精准分片 --  插入数据、精准查找使用
 */
@Slf4j
public class MonthPreciseShardingAlgorithm implements PreciseShardingAlgorithm<Date> {

    @Resource // 需要确保JdbcTemplate能被注入
    private JdbcTemplate jdbcTemplate;

    /**
     * 每个月分一片
     */
    @Override
    public String doSharding(Collection<String> collection, PreciseShardingValue<Date> preciseShardingValue) {
        //精确分片
        log.info("logic table name:{},rout column:{},column value:{}",
                preciseShardingValue.getLogicTableName(),
                preciseShardingValue.getColumnName(),
                preciseShardingValue.getValue());
        // 根据当前日期 来 分库分表
        Date date = preciseShardingValue.getValue();
        String format = DateUtil.format(date, "yyyyMM");
        // 选择表
        String tableName = preciseShardingValue.getLogicTableName() + "_" + format;
        log.info("Precise路由到的真实表:" + tableName);

        // 检查表是否存在，不存在则创建
//        if (!collection.contains(tableName)) {//检查逻辑错误
//            createTableIfAbsent(tableName);
//        }

        if (collection.contains(tableName))
            return tableName;

        throw new IllegalArgumentException();
    }

//    private void createTableIfAbsent(String tableName) {
//        log.info("匹配到的表：{} 当前未创建，自动创建", tableName);
//        jdbcTemplate.execute("CREATE TABLE if not exists `" + tableName + "` ( " +
//                "  `id` char(36) DEFAULT NOT NULL COMMENT '数据ID', " +
//                "  `sensor_id` varchar(36) NOT NULL COMMENT '传感器ID', " +
//                "  `water` decimal(8,2) DEFAULT NULL COMMENT '传感器数据', " +
//                "  `create_time` datetime DEFAULT NULL COMMENT '创建时间' " +
//                ") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;");
//    }
}

